/**
 * 
 */
$(document).ready(function () {
	/**
	 * Redirige l'utilisateur si il est déjà connectée
	 */
	if(auth != null && auth.connected == false) {
		window.location.href = "/index.html";
	}
	
	$.ajax('vol',{
		type:'GET',
		dataType: "json",
		data: {
			cmd:'listeVolHistoric',
        },
	}).done(function(data, testStatus, jqXHR){
		$("#volList").empty();
		for(var vol in data)
		{
			if(vol == "message") {}
			else if(vol == 0) {
				$("#leavingFrom").val(data[vol].leaving);
				$("#goingTo").val(data[vol].going);
				$("#departureTime").val(data[vol].time);
				$("#departureDate").val(data[vol].date);
			}
			else {
				$("#volList").append(
				"<tr class=\"data\"><td>" +
				data[vol].departureDate +
				" " + 
				data[vol].departureTime + 
				"</td><td>" +
				data[vol].arrivalDate +
				" " + 
				data[vol].arrivalTime + 
				"</td><td>" + 
				data[vol].duration +
				"</td><td>" +
				data[vol].availableSeats +
				"</td><td>" +
				data[vol].price +
				"</td><td>" +
				"<a class=\"btn btn-primary btn-block deleteVol\" href=\"\" " +
				"id=\"" +
				data[vol].id +
				"\">Réserver</a>" +
				"</td></tr>"		
				);
			}
		};
	}).fail(function(jqXHR, textStatus, errorThrown) {
        	setAlertMessage('Erreur!',errorThrown+ ' (' + textStatus +')','danger');
	});
	$("#btnSearchVol").click(function() {
		var formData = $("#searchVol-form").serializeArray();
		formData.push({name:"cmd",value:"searchVol"});
		$.ajax(
            "vol",{
            type: "POST",
			dataType: "json",
            data: formData,
        }).done(function(data, textStatus, jqXHR) {
        	$("#volList").empty();
        	if(data.length == 0) {
    			$("#volList").append("Pas de résultat");
    		}
			for(var vol in data)
			{
				$("#volList").append(
				"<tr class=\"data\"><td>" +
				data[vol].departureDate +
				" " + 
				data[vol].departureTime + 
				"</td><td>" +
				data[vol].arrivalDate +
				" " + 
				data[vol].arrivalTime + 
				"</td><td>" + 
				data[vol].duration +
				"</td><td>" +
				data[vol].availableSeats +
				"</td><td>" +
				data[vol].price +
				"</td><td>" +
				"<a class=\"btn btn-primary btn-block deleteVol\" href=\"\" " +
				"id=\"" +
				data[vol].id +
				"\">Book</a>" +
				"</td></tr>"		
				);
			};
        }).fail(function(jqXHR, textStatus, errorThrown) {
        	setAlertMessage('Erreur!',errorThrown+ ' (' + textStatus +')','danger');
        });
		return false;
	});
	
	$("#volList").delegate(".deleteVol", "click", function() {
		return false;
	});
});